package com.marsoft.test.controller;

import com.marsoft.test.constant.GuarantyConstant;
import com.marsoft.test.entity.MaximumAmountControllerEntity;
import com.marsoft.test.entity.MaximumAmountGuarantyInfoEntity;
import com.marsoft.test.entity.MaximumAmountServiceOutEntity;
import com.marsoft.test.exception.DefinitionException;
import com.marsoft.test.service.MaximumAmountService;
import com.marsoft.test.utils.CompareDateUtils;
import com.marsoft.test.utils.ResultMap;
import com.marsoft.test.validation.ValidationGroups;
import org.apache.commons.lang.StringUtils;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * MaximumAmountController
 *
 * @author jiaqiuyu
 * @date 2021/05/13
 */
@RestController
@RequestMapping("/maximum/amount")
public class MaximumAmountController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    MaximumAmountService maximumAmountService;

    @Autowired
    RedissonClient redissonClient;

    @PostMapping("/search")
    public ResultMap search(MaximumAmountControllerEntity maximumAmountControllerEntity){

        List<MaximumAmountServiceOutEntity> amountServiceOutEntity = maximumAmountService.search(maximumAmountControllerEntity);

        List<MaximumAmountControllerEntity> amountControllerEntityList = amountServiceOutEntity.stream().map(entity -> {

            MaximumAmountControllerEntity amountControllerEntity = new MaximumAmountControllerEntity();

            BeanUtils.copyProperties(entity, amountControllerEntity);

            return amountControllerEntity;
        }).collect(Collectors.toList());

        return ResultMap.ok().put(GuarantyConstant.RESULT_KEY_DATE,amountControllerEntityList);
    }

    @PostMapping("/save/maximumGuaranty")
    public ResultMap saveMaximumGuaranty(@Validated(ValidationGroups.SaveMaximumGuaranty.class) MaximumAmountControllerEntity maximumAmountControllerEntity,
            BindingResult result){

        // 如果页面校验出错
        if(result.hasErrors()){

            // 错误信息
            List<FieldError> list = result.getFieldErrors();

            // 收集错误信息
            Map<String, String> res = list.stream().
                    collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage,(o1,o2)->o1));

            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,res);
        }

        // 如果担保类型值不为0或1
        if(maximumAmountControllerEntity.getGuarantyType() != GuarantyConstant.GUARANTY_TYPE_VALUE_0
                && maximumAmountControllerEntity.getGuarantyType() != GuarantyConstant.GUARANTY_TYPE_VALUE_1){

            throw new DefinitionException("担保类型值被篡改");
        }

        // 如果担保方式值不为0或1或2
        if(maximumAmountControllerEntity.getGuarantyStyle() != GuarantyConstant.GUARANTY_STYLE_VALUE_0
                && maximumAmountControllerEntity.getGuarantyStyle() != GuarantyConstant.GUARANTY_STYLE_VALUE_1
                && maximumAmountControllerEntity.getGuarantyStyle() != GuarantyConstant.GUARANTY_STYLE_VALUE_2){

            throw new DefinitionException("担保方式值被篡改");
        }

        // 如果合同签订日大于合同生效日
        if(CompareDateUtils.compareDate(maximumAmountControllerEntity.getContStartDate(),
                maximumAmountControllerEntity.getContEffectDate())){

            ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"合同签订日不能大于合同生效日");
        }

        // 合同签订日不能大于到期日
        if(CompareDateUtils.compareDate(maximumAmountControllerEntity.getContStartDate(),
                maximumAmountControllerEntity.getEndDate())){

            ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"合同签订日不能大于到期日");
        }

        // 合同生效日不能大于到期日
        if(CompareDateUtils.compareDate(maximumAmountControllerEntity.getContEffectDate(),
                maximumAmountControllerEntity.getEndDate())){

            ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"合同生效日不能大于到期日");
        }

        maximumAmountService.saveMaximumGuaranty(maximumAmountControllerEntity);
        return ResultMap.ok();
    }

    @PostMapping("/delete/maximumGuaranty")
    public ResultMap deleteMaximumGuaranty(String guarantyContractNo) {

        int deleteFlag = maximumAmountService.daleteMaximumGuaranty(guarantyContractNo);

        // 如果没有纪录被删除
        if(deleteFlag <= 0){

            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"该条记录不存在或者已被删除");
    }

        return ResultMap.ok();
    }

    @PostMapping("/save/collateralInfo")
    public ResultMap saveCollateralInfo(@Validated(ValidationGroups.SaveMaximumGuaranty.class) MaximumAmountGuarantyInfoEntity amountGuarantyInfoEntity,
                                         BindingResult result){

        // 如果房屋状态为现房，则房屋所有权证号(即房产证)为必填项
        if(GuarantyConstant.HOME_STATE_EXISTING.equals(amountGuarantyInfoEntity.getHomeState())
                && amountGuarantyInfoEntity.getHouseCard()==null){

            logger.error("房屋所有权证号(即房产证)不能为空");
            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"房屋所有权证号(即房产证)不能为空");
        }

        // 如果评估日期大于登记日期
        if(CompareDateUtils.compareDate(amountGuarantyInfoEntity.getValuationDate(),
                amountGuarantyInfoEntity.getRecordDate())){

            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"评估日期不能大于登记日期");
        }

        // 如果使用面积大于建筑面积
        if(amountGuarantyInfoEntity.getUsingArea().
                compareTo(amountGuarantyInfoEntity.getBuildingArea()) > 0){

            logger.error("使用面积不能大于建筑面积");
            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"使用面积不能大于建筑面积");
        }

        // 如果所属土地使用权年限大于所属土地使用权剩余年限
        if(Integer.compare(amountGuarantyInfoEntity.getLandOwnershipYear(),
                amountGuarantyInfoEntity.getLandOwnershipRemainingYear()) > 0){

            logger.error("所属土地使用权年限不能大于所属土地使用权剩余年限");
            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"所属土地使用权年限不能大于所属土地使用权剩余年限");
        }

        // 如果房屋所在楼层大于总层数
        if(amountGuarantyInfoEntity.getHouseFloor() != null
                && amountGuarantyInfoEntity.getTotalLayer() != null
                && Integer.compare(amountGuarantyInfoEntity.getHouseFloor(),
                amountGuarantyInfoEntity.getTotalLayer()) > 0){

            logger.error("房屋所在楼层不能大于总层数");
            return ResultMap.error().put(GuarantyConstant.RESULT_KEY_ERROR,"房屋所在楼层不能大于总层数");
        }

        //单选项目check
        singleSelectionItemCheck(amountGuarantyInfoEntity);

        maximumAmountService.saveCollateralInfo(amountGuarantyInfoEntity);

        return ResultMap.ok();
    }

    /**
     * 单选项目check
     * @param amountGuarantyInfoEntity
     */
    private void singleSelectionItemCheck(MaximumAmountGuarantyInfoEntity amountGuarantyInfoEntity) {

        // 如果'是否为国家机关财产'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCountryMoney()!=null
                && amountGuarantyInfoEntity.getIsCountryMoney() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCountryMoney() != GuarantyConstant.FLAG_NO){

            logger.error("是否为国家机关财产值被篡改");

            throw new DefinitionException("是否为国家机关财产值被篡改");
        }

        // 如果'是否为政策性住房'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsPolicyHouse()!=null
                && amountGuarantyInfoEntity.getIsPolicyHouse() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsPolicyHouse() != GuarantyConstant.FLAG_NO){

            logger.error("是否为政策性住房值被篡改");

            throw new DefinitionException("是否为政策性住房值被篡改");
        }

        // 如果'是否为列为文物保护的古建筑或是有重要纪念意义的建筑物'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsArchitecture()!=null
                && amountGuarantyInfoEntity.getIsArchitecture() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsArchitecture() != GuarantyConstant.FLAG_NO){

            logger.error("是否为列为文物保护的古建筑或是有重要纪念意义的建筑物值被篡改");

            throw new DefinitionException("是否为列为文物保护的古建筑或是有重要纪念意义的建筑物值被篡改");
        }

        // 如果'是否为已依法公告在国家建设征用拆迁范围内的房地产'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsAccordanceDemolition()!=null
                && amountGuarantyInfoEntity.getIsAccordanceDemolition() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsAccordanceDemolition() != GuarantyConstant.FLAG_NO){

            logger.error("是否为已依法公告在国家建设征用拆迁范围内的房地产值被篡改");

            throw new DefinitionException("是否为已依法公告在国家建设征用拆迁范围内的房地产值被篡改");
        }

        // 如果'是否已提交房地产权证书'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitCertificate()!=null
                && amountGuarantyInfoEntity.getIsCommitCertificate() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitCertificate() != GuarantyConstant.FLAG_NO){

            logger.error("是否已提交房地产权证书值被篡改");

            throw new DefinitionException("是否已提交房地产权证书值被篡改");
        }

        // 如果'是否已提交房产的土地使用权证'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitLanduse()!=null
                && amountGuarantyInfoEntity.getIsCommitLanduse() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitLanduse() != GuarantyConstant.FLAG_NO){

            logger.error("是否已提交房产的土地使用权证值被篡改");

            throw new DefinitionException("是否已提交房产的土地使用权证值被篡改");
        }

        // 如果'是否已提交房产的出租合同与相关登记证明'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitRentprove()!=null
                && amountGuarantyInfoEntity.getIsCommitRentprove() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitRentprove() != GuarantyConstant.FLAG_NO){

            logger.error("是否已提交房产的出租合同与相关登记证明值被篡改");

            throw new DefinitionException("是否已提交房产的出租合同与相关登记证明值被篡改");
        }

        // 如果'是否已提交房产的土地使用权出让合同'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitCertificateContract()!=null
                && amountGuarantyInfoEntity.getIsCommitCertificateContract() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitCertificateContract() != GuarantyConstant.FLAG_NO){

            throw new DefinitionException("是否已提交房产的土地使用权出让合同值被篡改");
        }

        // 如果'是否已存在售出的预告登记'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsHaveSaleRegistration()!=null
                && amountGuarantyInfoEntity.getIsHaveSaleRegistration() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsHaveSaleRegistration() != GuarantyConstant.FLAG_NO){

            throw new DefinitionException("是否已存在售出的预告登记值被篡改");
        }

        // 如果'是否已提交商品房预购（售）合同'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitHousesalecont()!=null
                && amountGuarantyInfoEntity.getIsCommitHousesalecont() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitHousesalecont() != GuarantyConstant.FLAG_NO){

            throw new DefinitionException("是否已提交商品房预购（售）合同值被篡改");
        }

        // 如果'是否已提交房型图复印件'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitPicturecopy()!=null
                && amountGuarantyInfoEntity.getIsCommitPicturecopy() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitPicturecopy() != GuarantyConstant.FLAG_NO){

            throw new DefinitionException("是否已提交房型图复印件值被篡改");
        }

        // 如果'是否已提交抵押物共有人出具的同意抵押的书面授权文件'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitAuthorization()!=null
                && amountGuarantyInfoEntity.getIsCommitAuthorization() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitAuthorization() != GuarantyConstant.FLAG_NO){

            throw new DefinitionException("是否已提交抵押物共有人出具的同意抵押的书面授权文件值被篡改");
        }

        // 如果'是否已提交房屋租赁合同'项目被选择了但是值不为0或1
        if(amountGuarantyInfoEntity.getIsCommitHousecontract()!=null
                && amountGuarantyInfoEntity.getIsCommitHousecontract() != GuarantyConstant.FLAG_YES
                && amountGuarantyInfoEntity.getIsCommitHousecontract() != GuarantyConstant.FLAG_NO){


            throw new DefinitionException("是否已提交房屋租赁合同值被篡改");
        }
    }

}
